package model;

import java.util.ArrayList;
import org.newdawn.slick.SlickException;


public final class Level 
{

	private ArrayList<Item> items;
	private double points;
	private double nextLvlPartAt = -1;
	
	public Level()
	{
		items = new ArrayList<Item>();
		points = -1;
		
		while (nextLvlPartAt <= 0)
		{
			LevelPartial lp = LevelPartialFactory.getLevelPartial(points);
			items.addAll(lp.getItems());
			schiebeSichtfenster(Math.min(lp.getHeight(), -nextLvlPartAt));
			nextLvlPartAt += lp.getHeight();
		}

	}
	
	public double getPoints()
	{
		return points;
	}

	public void setPoints(double points)
	{
		this.points = points;
	}

	Item[] update() {
		cleanUpItems();

		addItems();
			
		return items.toArray(new Item[items.size()]);
	}
	
	public void schiessen(double startX, double startY, double angle) {
		try
		{
			items.add(new Bullet(startX, startY, angle));
		}
		catch (SlickException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void cleanUpItems() {
		ArrayList<Item> itemsToRemove = new ArrayList<Item>();
		
		for(Item item : items) {
			if(item.getY() + item.getHeight() < 0) itemsToRemove.add(item);
		}
		
		for(Item itemToRemove : itemsToRemove) {
			items.remove(items.indexOf(itemToRemove));
		}
	}
	
	private void addItems()
	{
		while (nextLvlPartAt <= points)
		{
			LevelPartial lp = LevelPartialFactory.getLevelPartial(points);
			items.addAll(lp.getItems());
			nextLvlPartAt += lp.getHeight();
		}	
	}
	
	public void schiebeSichtfenster(double y) 
	{
		for (Item item: items)
		{
			item.move(y);
		}
		setPoints(getPoints() + y);
	}
	
}
